<template>
  <div class="content_index">
    <div class="ci_header">
      <div class="ci_left sec-title">
        <el-icon
          style="vertical-align: middle; display: unset; cursor: pointer"
          @click="backList()"
          ><Back
        /></el-icon>
        <!-- <span>{{ route.name }}</span> -->
        <span>存证明细</span>
      </div>
    </div>
    <div class="ci_content" style="margin: 12px 16px">
      <el-form
        ref="DetailFormRef"
        label-width="140px"
        :model="DetailForm"
        style="width: calc(100% - 16px)"
      >
        <el-form-item label="存证编号：">
          {{ DetailObj.evidenceId }}
        </el-form-item>
        <el-form-item label="存证名称：">
          {{ DetailObj.evidenceName }}
        </el-form-item>
        <el-form-item label="存证类型：">
          {{
            DetailObj.evidenceType === "0"
              ? "哈希"
              : DetailObj.evidenceType === "1"
              ? "图片"
              : DetailObj.evidenceType === "2"
              ? "文档"
              : DetailObj.evidenceType === "3"
              ? "音频视频"
              : DetailObj.evidenceType === "4"
              ? "混合类型"
              : "--"
          }}
        </el-form-item>
        <el-form-item label="是否加密：">
          {{
            DetailObj.useEncrypt === "0"
              ? "不加密"
              : DetailObj.useEncrypt === "1"
              ? "加密"
              : "--"
          }}
        </el-form-item>
        <el-form-item label="交易哈希：">
          {{ DetailObj.txId }}
        </el-form-item>
        <el-form-item label="交易时间：">
          {{ DetailObj.txTime }}
        </el-form-item>
        <el-form-item label="存证状态：">
          {{
            DetailObj.status === "0"
              ? "存证中"
              : DetailObj.status === "1"
              ? "存证成功"
              : "--"
          }}
        </el-form-item>
        <el-form-item label="区块号：">
          {{ DetailObj.blockNum }}
        </el-form-item>
        <el-form-item label="区块哈希：">
          {{ DetailObj.blockHash }}
        </el-form-item>
        <el-form-item label="交易内容：">
          <div class="box">
            <div class="left_txContent">
              {{ DetailObj.txContent }}
            </div>
            <div class="rigth_txContent">
              <pre>{{ formatTxContent }}</pre>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="被签名数据：">
          <div class="wordWrap">
            {{ DetailObj.evidenceData }}
          </div>
        </el-form-item>
        <el-form-item label="签名：">
          <div class="wordWrap">
            {{ DetailObj.signature
            }}<el-button
              style="margin-left: 10px"
              @click.prevent="checkSign"
              type="primary"
              >验签</el-button
            >
          </div>
        </el-form-item>
        <el-form-item label="公钥：">
          {{ DetailObj.pubKey }}
        </el-form-item>
        <el-form-item label="文件存证函：">
          <span
            style="color: #2a82e4; cursor: pointer"
            v-down="{ url: DetailObj.evidenceCert, fileName: '存证函.png' }"
          >
            {{ DetailObj.evidenceCert ? "存证函.png" : "--" }}</span
          >
        </el-form-item>
        <el-form-item label="文件信息：">
          <div
            class="file_cn"
            v-for="(item, index) in DetailObj.fileInfo"
            :key="index"
          >
            <div>文件名称:{{ item.name }}</div>
            <div>
              文件url:{{ item.url }}
              <el-button
                v-if="DetailObj.useEncrypt === '1'"
                @click.prevent="deciphering(item.url)"
                type="primary"
                >解密</el-button
              >
            </div>
            <div>文件哈希:{{ item.hash }}</div>
          </div>
        </el-form-item>

        <!-- <div>
          <pre>{{ DetailObj.txContent}}</pre>
        </div> -->

        <el-form-item>
          <el-dialog
            title="解密"
            :close-on-click-modal="false"
            :model-value="dialogVisible"
            :destroy-on-close="true"
            @close="clearForm"
          >
            <div>
              <el-form
                label-position="right"
                ref="pswFormRef"
                label-width="120px"
                :model="pswForm"
                :rules="rules"
              >
                <el-form-item label="存证编号" prop="evidenceId">
                  <el-tooltip
                    effect="light"
                    :content="DetailObj ? DetailObj.evidenceId : '--'"
                    placement="top"
                  >
                    <div class="ellipsis">
                      {{ DetailObj ? DetailObj.evidenceId : "--" }}
                    </div>
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="文件url" prop="fileUrl">
                  <el-tooltip
                    effect="light"
                    :content="decryptUrl ? decryptUrl : '--'"
                    placement="top"
                  >
                    <div class="ellipsis">
                      {{ decryptUrl ? decryptUrl : "--" }}
                    </div>
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input
                    v-model="pswForm.password"
                    type="password"
                    placeholder="请输入密码"
                    show-password
                  ></el-input>
                </el-form-item>
              </el-form>
            </div>
            <div slot="footer" class="dialog-footer center">
              <el-button @click.prevent="decipheringConfirm" type="primary"
                >确定</el-button
              >
              <el-button plain @click="cancel">取消</el-button>
            </div>
          </el-dialog>
          <el-dialog
            title="验签"
            :close-on-click-modal="false"
            :model-value="checkSignDialogVisible"
            :destroy-on-close="true"
            @close="clearSignForm"
          >
            <el-tooltip
              effect="light"
              :content="DetailObj.evidenceData"
              placement="top"
            >
              <div class="Sign_content">
                <div class="Sign_content_key">被签名数据:</div>
                <div class="Sign_content_data">
                  {{ DetailObj.evidenceData }}
                </div>
              </div>
            </el-tooltip>
            <el-tooltip
              effect="light"
              :content="DetailObj.signature"
              placement="top"
            >
              <div class="Sign_content">
                <div class="Sign_content_key">签名:</div>
                <div class="Sign_content_data">{{ DetailObj.signature }}</div>
              </div>
            </el-tooltip>
            <el-tooltip
              effect="light"
              :content="DetailObj.pubKey"
              placement="top"
            >
              <div class="Sign_content">
                <div class="Sign_content_key">公钥:</div>
                <div class="Sign_content_data">{{ DetailObj.pubKey }}</div>
              </div>
            </el-tooltip>
            <div class="Sign_content">
              <div class="Sign_content_key">签名算法:</div>
              <div class="Sign_content_data">国密SM2</div>
            </div>
            <div class="Sign_content">
              <div class="Sign_content_key">验签结果:</div>
              <div
                class="Sign_content_data"
                :class="
                  checkSignStatus === '验签成功'
                    ? 'green'
                    : checkSignStatus === '验签失败'
                    ? 'red'
                    : '--'
                "
              >
                {{ checkSignStatus }}
              </div>
            </div>

            <div slot="footer" class="dialog-footer center">
              <el-button
                @click.prevent="checkSignDialogVisible = false"
                type="primary"
                >确定</el-button
              >
              <el-button plain @click="checkSignDialogVisible = false"
                >取消</el-button
              >
            </div>
          </el-dialog>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script setup>
import { reactive, ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { isValidPwd } from "@/utils/validate";
import axios from "@/utils/axios";
import { shaCrypto } from "@/utils/crypto";
import {
  detailEvidenceFile,
  evidenceFileDecrypt,
  evidenceSignatureDecrypt,
} from "@/api/existingEvidence";
import { ElMessage } from "element-plus";
import { saveFile, deepJSON } from "@/utils/tool";
const router = useRouter();
const route = useRoute();
const dialogVisible = ref(false);
const checkSignDialogVisible = ref(false);
const checkSignStatus = ref("");
const decryptUrl = ref("");
const backList = () => {
  router.go(-1);
};
const formatTxContent = ref({});
const pswForm = reactive({
  evidenceId: "",
  fileUrl: "",
  password: "",
});
const pswFormRef = ref("pswForm");
/** 密码校验 */
const validatePwd = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("密码不能为空"));
  } else {
    // 校验密码
    if (!isValidPwd(value)) {
      rule.message =
        "8~64位字符，允许大、小写英文字母、特殊字符、数字，且至少3种组合";
      callback(new Error());
    } else {
      callback();
      // 注意，这个空的callback非常重要，没有它作为结束，整个校验会出问题
    }
  }
};
const rules = reactive({
  password: [
    {
      required: true,
      validator: validatePwd,
      message:
        "8~64位字符，允许大、小写英文字母、特殊字符、数字，且至少3种组合",
      trigger: "blur",
    },
    {
      min: 8,
      max: 64,
      message:
        "8~64位字符，允许大、小写英文字母、特殊字符、数字，且至少3种组合",
      trigger: "blur",
    },
  ],
});
const DetailForm = reactive({});
const DetailObj = ref({});
const DocumentDetailInfo = async () => {
  let parmars = {
    evidenceId: route.query.id,
  };
  const { success, msg, data } = await detailEvidenceFile(parmars);
  if (success) {
    DetailObj.value = data || {};
    formatTxContent.value = deepJSON({}, JSON.parse(DetailObj.value.txContent));
  } else {
    ElMessage.error(msg || "明细获取失败,请稍后再试");
  }
};
const clearForm = () => {
  dialogVisible.value = false;
  pswForm.password = "";
};
const clearSignForm = () => {
  checkSignDialogVisible.value = false;
};
const decipheringConfirm = () => {
  pswFormRef.value?.validate(async (valid) => {
    if (valid) {
      let parmars = {
        ...pswForm,
      };
      parmars.evidenceId = DetailObj.value ? DetailObj.value.evidenceId : "";
      parmars.fileUrl = decryptUrl.value ? decryptUrl.value : "";
      const res = await evidenceFileDecrypt(parmars);
      if (res.data.type === "application/json") {
        //返回的错误消息是Blob格式，现在转为json,
        const file = new FileReader();
        file.readAsText(res.data, "utf-8");
        file.onload = () => {
          const data = JSON.parse(file.result);
          ElMessage.error(data.msg || "解密失败,请稍后再试");
          dialogVisible.value = false;
        };
      } else {
        const fileName = decodeURI(
          res.headers?.get("content-disposition")
        ).split("filename=")[1];
        const fileNameDecode = decodeURI(
          decodeURIComponent(escape(fileName)),
          "UTF-8"
        ); //进行解码
        saveFile(fileNameDecode, res.data);
        dialogVisible.value = false;
        ElMessage.success("解密成功");
      }
    } else {
      return false;
    }
  });
};
const checkSign = async () => {
  let parmars = {
    evidenceData: DetailObj.value.evidenceData,
    signature: DetailObj.value.signature,
    pubKey: DetailObj.value.pubKey,
  };
  checkSignDialogVisible.value = true;
  const { success, msg } = await evidenceSignatureDecrypt(parmars);
  if (success) {
    checkSignStatus.value = msg || "验签成功";
    // ElMessage.success(msg || "验签成功");
  } else {
    checkSignStatus.value = msg || "验签失败,请稍后再试";
    // ElMessage.error(msg || "验签失败,请稍后再试");
  }
};
const cancel = () => {
  dialogVisible.value = false;
};
const deciphering = (url) => {
  dialogVisible.value = true;
  decryptUrl.value = url;
};
onMounted(() => {
  DocumentDetailInfo();
});
</script>

<style lang="scss" scoped>
@import "../../assets/css/cindex.scss";
:deep .el-upload-list--picture-card .el-upload-list__item-actions span + span {
  margin-left: 0.5em;
}
.add_icon {
  font-size: 18px;
  // margin-left: 10px;
  cursor: pointer;
  height: 100%;
}
.delete_icon {
  font-size: 18px;
  margin-left: 10px;
  cursor: pointer;
  height: 100%;
}
.box {
  display: flex;
  .left_txContent {
    // width: 200px;
    width: 50%;
    padding: 20px;
    // height: 200px;
    // background: pink;
    border-radius: 8px;
    border: 1px solid #d6e9c6;
    word-break: break-word;
    margin-right: 10px;
  }
  .rigth_txContent {
    width: 50%;
    padding: 20px;

    // width: 200px;
    // height: 200px;
    // background: red;
    border-radius: 8px;
    border: 1px solid #d6e9c6;
    word-break: break-word;
  }
}
.file_cn {
  // width: 130px;
  width: 100%;
  font-size: 14px;
  //   text-align: right;
  // margin-left: 70px;
  margin-bottom: 5px;
  padding: 10px;
  border-radius: 4px;
  border: 1px dashed #a6a6a6;
  div {
    margin-bottom: 15px;
  }
}
.Sign_content {
  display: flex;
  font-size: 14px;
  .Sign_content_key {
    display: inline-flex;
    justify-content: flex-end;
    align-items: flex-start;
    flex: 0 0 auto;
    height: 32px;
    line-height: 32px;
    padding: 0 12px 0 0;
    box-sizing: border-box;
    width: 90px;
  }
  .Sign_content_data {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    flex: 1;
    line-height: 32px;
    position: relative;
    min-width: 0;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }
}

.red {
  color: red;
}
.green {
  color: green;
}
.el-form-item .el-form-item {
  width: 100%;
  margin-bottom: 20px;
}
.wordWrap {
  word-break: break-word;
}
:deep .el-descriptions .el-descriptions__label {
  display: inline-block;
  width: 100px;
  text-align: right;
}
</style>
